#!/usr/bin/python

import getpass
import sys
import os
from gecoc import gecolib


def test_passwd(gso, master):
    wp = gso.test_passwords(master)
    if wp:
        print "wrong passwords"
        for i in wp:
            print i

def export(gso, filename):
    out = open(filename, 'w')
    out.write(gso.export())

def inp(prompt, default="", function=raw_input):
    value = function(prompt)
    if not value:
        value = default

    return value

def inp_p(prompt, default=""):
    return inp(prompt, default, getpass.getpass)

server = inp("server (https://localhost:4343): ", "https://localhost:4343")
user = inp("user: ", os.environ["USER"])
passwd = inp_p("passwd: ")
print "----"
master1 = inp_p("actual master (default user password): ", passwd)
master2 = inp_p("new master: ")
master3 = inp_p("new master again: ")

if master2 != master3:
    print "new master not the same"
    sys.exit(-1)

gso = gecolib.GSO(xmlrpc_server=server)
try:
    gso.auth(user, passwd)
except:
    print "wrong server, username or password"
    sys.exit(-1)

try:
    export(gso, "/tmp/geco.backup")
    print "backup created in /tmp/geco.backup"
except Exception, e:
    print "can't create backup, aborting", e

cont = inp("Continue? y/N: ", "N")

if cont in 'yY':
    print "changing..."
    gso.change_master(master1, master2)
    test_passwd(gso, master2)
    print "changed"
else:
    print "not changed"
